from ankiqt import mw
from ankiqt import ui
from anki.utils import stripHTML

from PyQt4.QtCore import *
from PyQt4.QtGui import *


from sys import path
import os
ankitweetpath = os.path.dirname(os.path.abspath(__file__)) 
ankitweetlib =  os.path.join(ankitweetpath , 'ankitweet')
path.insert(0,ankitweetlib)

import twitter
import oauth2 as oauth
import oauthtwitter
import urllib
import twoauth
import webbrowser

consumer_key = "CwHVQQ6la4AnTM53f6BAA"
consumer_secret = "Pgcfx92HwerK2Y9JACqRSGvS3aWD36DVgVnFOgSNbHI"

def newEventHandler(evt):
    if (evt):
        key = unicode(evt.text())
    else:
        return oldEventHandler(evt)
    

    ### Don't set any shortcuts if not showing question or answer
    if not (mw.state == "showQuestion") and not (mw.state == "showAnswer"): 
        return oldEventHandler(evt)

    
    if key=="t":                           # add shortcuts to bury the fact
        access_token, access_token_secret = oauthInit()
        # send message
        message = u'#English ' + stripHTML(mw.currentCard.answer)
        text, ok = QInputDialog.getText(mw, 'Input Dialog', 'The next line is being sent to Twitter', QLineEdit.Normal, message)
        if ok:
            evt.accept()            
            message = text.toUtf8()
            params = urllib.urlencode({'status': message})
            consumer = oauth.Consumer(key=consumer_key, secret=consumer_secret)
            token = oauth.Token(access_token, access_token_secret)
            client = oauth.Client(consumer, token)
            post_url  = 'http://twitter.com/statuses/update.xml'
            client.request(post_url, "POST", params)
            ui.utils.showInfo("Sent to twitter: %s" % message )

    return oldEventHandler(evt)

def  oauthInit():
    access_token_path = os.path.join(ankitweetlib , 'access_token')
    access_token = ''
    access_token_secret = ''
    if  os.path.isfile(access_token_path) == True:
        f = open(access_token_path, 'r')
        access_token = f.readline().strip()
        access_token_secret = f.readline().strip()

    else:
        QMessageBox.information(mw,'Ankitweet: Initialization', 'User authorization. \nPlease login to twitter in your  browser before pressing Ok.')

        # Get Request Token and PIN URL
        oauth = twoauth.oauth(consumer_key, consumer_secret)
        req_token = oauth.request_token()
        url = oauth.authorize_url(req_token)
        webbrowser.open(url) 
        pin, ok = QInputDialog.getText(mw, 'PIN code',  'Allow AnkiTweet on your account and enter 7-digit PIN code displayed in your browser')

        if ok:
            acc_token = oauth.access_token(req_token, pin)
            QMessageBox.information(mw,'Initialization', 'Successfully authorized: %s \nNow you can tweet by pressing T key on preview.'   % acc_token["screen_name"])
            f = open(access_token_path, 'w')
            access_token = acc_token["oauth_token"]
            access_token_secret = acc_token["oauth_token_secret"]
            f.write(acc_token["oauth_token"]+"\n")
            f.write(acc_token["oauth_token_secret"])

    return access_token , access_token_secret


# Authorization of twitter
oauthInit()

oldEventHandler = mw.keyPressEvent
mw.keyPressEvent = newEventHandler
mw.registerPlugin("ankitweet", 7)
